package com.lpf.MyGameSaveBackup.GameSaveBackup.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.log.StaticLog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lpf.MyGameSaveBackup.GameSaveBackup.vo.GameSaveBackVo;
import com.lpf.MyGameSaveBackup.alist.service.AlistService;
import com.lpf.MyGameSaveBackup.config.service.GlobalConfigService;

import java.io.File;
import java.util.Comparator;
import java.util.Date;

public class GameSaveBackupService {

    //游戏存档备份
    public static boolean backup(GameSaveBackVo gameSaveBackVo) throws Exception {
        //将游戏存档目录下面的所有文件压缩成压缩包临时放在临时目录下，压缩包命名格式为backup_yyyyMMddHHmmss.zip
        String backupFileName = "backup_"+ DateUtil.format(new Date(), DatePattern.PURE_DATETIME_FORMAT);
        File zipFile = new File("GameSaveBack" + File.separator + backupFileName+".zip");
        ZipUtil.zip(gameSaveBackVo.getGameSavePath(), zipFile.getAbsolutePath());
        if ("info".equals(GlobalConfigService.GlobalConfig.getLogLevel())){
            StaticLog.info("游戏存档备份压缩文件临时存放路径：{}",zipFile.getAbsolutePath());
        }
        //将存档压缩包上传到alist,存放路径为{backupPath}/{gameEnName}/backup_yyyyMMddHHmmss.zip
        String path = gameSaveBackVo.getBackupPath()+"/"+gameSaveBackVo.getGameEnName()+"/"+backupFileName+".zip";
        AlistService.uploadFile(path,zipFile,false);
        if ("info".equals(GlobalConfigService.GlobalConfig.getLogLevel())){
            StaticLog.info("将游戏存档备份到alist成功 存放路径为：{}",path);
        }
        zipFile.deleteOnExit();
        return true;
    }

    //获取云端游戏存档备份集合
    public static JSONArray getBackupFileList(GameSaveBackVo gameSaveBackVo,Integer current,Integer size){
        if (null == current)
            current = 1;
        if (null == size)
            size = 10;
        String path = gameSaveBackVo.getBackupPath()+"/"+gameSaveBackVo.getGameEnName();
        //查询出云端备份目录下所有文件
        JSONObject fsListResult = AlistService.fsList(path,null ,current,size,false);
        if (null == fsListResult && CollUtil.isNotEmpty(fsListResult.getJSONArray("content"))){
            StaticLog.info("云端备份文件不存在");
            return null;
        }
        else {
            JSONArray fsList = fsListResult.getJSONArray("content");
            //根据名称排序,根据名称降序排序，从最近时间到最远时间
            if (CollUtil.isNotEmpty(fsList))
                fsList.sort(Comparator.comparing(obj -> ((JSONObject) obj).getString("name")).reversed());
            return fsList;
        }
    }

    //游戏存档恢复
    public static boolean recovery(GameSaveBackVo gameSaveBackVo,String backupFileName,boolean backup) throws Exception {
        String path = gameSaveBackVo.getBackupPath()+"/"+gameSaveBackVo.getGameEnName()+"/"+backupFileName;
        File backupFile = new File("GameSaveBack" + File.separator + backupFileName);
        AlistService.downloadFile(path,backupFile.getAbsolutePath());
        if ("info".equals(GlobalConfigService.GlobalConfig.getLogLevel())){
            StaticLog.info("将游戏存档下载到本地成功 存放路径为：{}",backupFile.getAbsolutePath());
        }

        //将本地游戏存档目录所有文件做一下备份
        String recoveryBackupFileName = "recoveryBackup_"+ DateUtil.format(new Date(), DatePattern.PURE_DATETIME_FORMAT);
        File recoveryBackupFile = new File("GameSaveBack" + File.separator + recoveryBackupFileName+".zip");
        //判断文件夹是否存在
        if (new File(gameSaveBackVo.getGameSavePath()).exists()){
            ZipUtil.zip(gameSaveBackVo.getGameSavePath(), recoveryBackupFile.getAbsolutePath());
            if ("info".equals(GlobalConfigService.GlobalConfig.getLogLevel())){
                StaticLog.info("将本地游戏存档备份 存放路径为：{}",recoveryBackupFile.getAbsolutePath());
            }

            //删除本地游戏存档目录所有文件
            for (File file : FileUtil.ls(gameSaveBackVo.getGameSavePath())){
                FileUtil.del(file);
            }
        }
        else {
            if ("info".equals(GlobalConfigService.GlobalConfig.getLogLevel())){
                StaticLog.info("不存在本地游戏存档，直接覆盖");
            }
        }


        //将云端的备份解压到本地游戏存档目录中
        try {
            ZipUtil.unzip(backupFile.getAbsolutePath(),gameSaveBackVo.getGameSavePath());
            //不需要保存原有存档
            if (!backup)
                FileUtil.del(recoveryBackupFile.getAbsolutePath());
            backupFile.deleteOnExit();
            return true;
        }
        catch (Exception e){
            e.printStackTrace();
            StaticLog.error("将云端存档恢复到本地失败：{}",e);
            //如果存档解压失败，恢复原先的存档
            ZipUtil.unzip(recoveryBackupFile.getAbsolutePath(),gameSaveBackVo.getGameSavePath());
            recoveryBackupFile.deleteOnExit();
            backupFile.deleteOnExit();
        }
        return false;
    }

    public static boolean delete(GameSaveBackVo gameSaveBackVo,String backupFileName) throws Exception {
        String path = gameSaveBackVo.getBackupPath()+"/"+gameSaveBackVo.getGameEnName()+"/";
        AlistService.del(backupFileName,path);
        if ("info".equals(GlobalConfigService.GlobalConfig.getLogLevel())){
            StaticLog.info("删除{} -游戏云端存档: 路径为：{}",gameSaveBackVo.getGameName(),path+backupFileName);
        }
        return true;
    }
}
